import regeneratorRuntime from '../../lib/runtime/runtime'

import { request } from "../../request/index"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: []
  },
  GoodsInfo: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { goods_id } = options;
    console.log(goods_id);
    this.getGoodsDetail(goods_id)
  },

  async getGoodsDetail(goods_id) {
    const goodsObj = await request({ url: "/goods/detail", data: { goods_id } });
    console.log(goodsObj);
    this.GoodsInfo = goodsObj;
    this.setData({
      // goodsObj: goodsObj.data.message
      // 性能优化
      goodsObj: {
        goods_name: goodsObj.data.message.goods_name,
        goods_price: goodsObj.data.message.goods_price,
        goods_introduce: goodsObj.data.message.goods_introduce,
        pics: goodsObj.data.message.pics
      }
    })
  },

  // 点击轮播图放大预览
  handelePreviewImage(e) {
    const urls = this.GoodsInfo.data.message.pics.map(v => v.pics_mid);
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current: current,
      urls: urls,
    });
  },

  // 点击加入购物车
  handleCartAdd() {
    // 获取缓存中的 购物车数组
    let cart = wx.getStorageSync('cart') || [];

    // 判断缓存中的购物车 数组
    let index = cart.findIndex(v => v.data.message.goods_id === this.GoodsInfo.goods_id)
    if (index === -1) {
      this.GoodsInfo.num = 1;
      this.GoodsInfo.checked = true;
      cart.push(this.GoodsInfo)
    } else {
      cart[index].num++;
    }
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true,
      success: (result) => {

      },
      fail: () => { },
      complete: () => { }
    });
  }
})